package com.example.widget_lib.widget.touch;

import com.example.widget_lib.utils.PxUtil;
import com.example.widget_lib.utils.Util;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.multimodalinput.event.TouchEvent;

/**
 * 下拉刷新组件
 */
public class MatrixView extends ComponentContainer implements
        Component.TouchEventListener {

    public static final float OVER_SCALE = 1.5f;
    public int mPullRefreshHeight = 200;
    /**
     * 最小阻尼，用户越往下拉，越不跟手
     */
    public float minDamp = 1.6f;
    /**
     * 最大阻尼
     */
    public float maxDamp = 2.2f;
    private int srceenWidth;
    private int screenHeight;
    private PixelMap mBitmap;
    private float mBigScale, mSmallScale;
    private float mOriginalOffsetX, mOriginalOffsetY;
    private GestureDetector mGestureDetector;
    private int mLastX;
    private int mLastY;
    private Size originSize;
    private Image image;
    private AnimatorValue mScaleAnimator;
    private boolean mIsBig = false;
    private int mOffsetX, mOffsetY;
    private int titlebar;
    private int viewHeight;

    public MatrixView(Context context, AttrSet attrSet) {
        super(context, attrSet, "");
        titlebar = (int) PxUtil.vp2px(45 + 22);
        srceenWidth = PxUtil.screenWidth();
        screenHeight = PxUtil.screenHeight();
        // 调用setTouchEventListener，让onTouchEvent方法执行
        setTouchEventListener(this);
        // 如果是正在刷新状态，则不允许在滑动的时候改变状态
        // 用户手动下拉触发滑动，moveDown方法的第二个参数传false
        GestureDetector.OnGestureListener gestureDetector = new GestureDetector.OnGestureListener() {
            @Override
            public boolean onScroll(TouchEvent e1, TouchEvent e2, float distanceX, float distanceY) {
                mOffsetX += -distanceX;
                mOffsetY += -distanceY;
                image.setTranslation(mOffsetX, mOffsetY);



                return false;
            }

            @Override
            public void onDoubleTap() {
                mIsBig = !mIsBig;
                getAnimator().start();
            }
        };

        mGestureDetector = new GestureDetector(gestureDetector);

        mBitmap = Util.getAvatar(this, (int) PxUtil.vp2px(220));

        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                viewHeight = getHeight();
                getContext().getUITaskDispatcher().asyncDispatch(() -> {
                    Size size = mBitmap.getImageInfo().size;
                    mOriginalOffsetX = (getWidth() - size.width) >> 1;
                    mOriginalOffsetY = (getHeight() - size.height) >> 1;
                    if ((float) size.width / size.height > (float) getWidth() / getHeight()) { // 图片宽高比 > view的宽高比
                        mSmallScale = (float) getWidth() / size.width;
                        mBigScale = (float) getHeight() / size.height + OVER_SCALE;
                    } else {
                        mSmallScale = (float) getHeight() / size.height;
                        mBigScale = (float) getWidth() / size.width + OVER_SCALE;
                    }
                    originSize = new Size();
                    originSize.width = (int) (size.width * mSmallScale);
                    originSize.height = (int) (size.height * mSmallScale);
                    createChild(originSize);
                });
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {

            }
        });
    }

    private void createChild(Size originSize) {
        PixelMap.InitializationOptions opts = new PixelMap.InitializationOptions();
        opts.size = new Size(originSize.width, originSize.height);
        PixelMap pixelMap = PixelMap.create(mBitmap, opts);
        image = new Image(getContext());
        image.setImageElement(new PixelMapElement(pixelMap));
        image.setLayoutConfig(new LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_PARENT));
        image.setPivot(srceenWidth >> 1, screenHeight >> 1);
        image.setTop((getHeight() - originSize.height) >> 1);
        this.addComponent(image);
    }

    /**
     * 处理分派给组件的触摸事件，要想该方法执行，需要调用setTouchEventListener方法，这里在构造方法里面调用了setTouchEventListener方法
     * @param component view
     * @param ev 触摸事件
     * @return 是否处理
     */
    @Override
    public boolean onTouchEvent(Component component, TouchEvent ev) {
        return mGestureDetector.onTouchEvent(ev);
    }

    public AnimatorValue getAnimator() {
        if (mScaleAnimator == null) {
            mScaleAnimator = new AnimatorValue();
            mScaleAnimator.setDuration(200);
            mScaleAnimator.setValueUpdateListener((animatorValue, v) -> {
                float scale;
                float bigScale = mBigScale - mSmallScale - 1;
                if (mIsBig) {
                    scale = 1 + v * (bigScale - 1);
                } else {
                    scale = bigScale + v * (1 - bigScale);
                }
                setScale(scale, scale);
            });
        }
        return mScaleAnimator;
    }
}
